package com.ruoyi.web.controller.baodao.controller;

import com.ruoyi.baodao.entity.*;
import com.ruoyi.baodao.mapper.BDMapper;
import com.ruoyi.baodao.mapper.LinkTemplateMapper;
import com.ruoyi.baodao.mapper.MFGoods9999Mapper;
import com.ruoyi.baodao.mapper.MFGoodsLinkMapper;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.web.controller.baodao.service.GoodsLinksService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.Inflater;

// 新增


@Slf4j
@Controller
@RequestMapping("baodao/demo02")
public class Demo2Controller extends BaseController {
    @Autowired
    MFGoods9999Mapper mfGoods9999Mapper;
    @Autowired
    MFGoodsLinkMapper mfGoodsLinkMapper;
    @Autowired
    BDMapper bdMapper;
    @Autowired
    GoodsLinksService goodsLinksService;
    @Autowired
    LinkTemplateMapper linkTemplateMapper;


    private String prefix = "baodao/demo02";

    @GetMapping()
    public String operlog()
    {
        return prefix + "/demo02";
    }

    /**
     * 药品主档
     */
    @PostMapping("/list")
    @ResponseBody
    @DataSource(value = DataSourceType.SLAVE)
    public TableDataInfo list(MFGoods9999 mfGoods9999, String flag)
    {
        // 获取 用户名 和  用户 部门
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        // 取部门编号（门店号）
        sysUser.getDept();
        String shopId = sysUser.getDept().getDeptName();
        log.info("登录用户信息" +sysUser.toString());
        log.info("登录用户：" + sysUser.getLoginName() + "所属门店" + sysUser.getDept().getDeptName() );
        log.info("查询药品主档,标识参数flag ：{}",flag);
        logger.info("查询药品主档,参数:{}",mfGoods9999.getPlucode());
        logger.info("查询药品主档,参数:{}",mfGoods9999.getClassname());
        List<MFGoodsLink> mfGoodsLinks = mfGoodsLinkMapper.selectByExample(new MFGoodsLinkExample());
        startPage(); //分页

        MFGoods9999Example mfGoods9999Example = new MFGoods9999Example();
        MFGoods9999Example.Criteria criteria = mfGoods9999Example.createCriteria();
        if(mfGoods9999.getPlucode() != null && !mfGoods9999.getPlucode().equals("")){
            criteria.andPlucodeEqualTo(mfGoods9999.getPlucode());}
        if(mfGoods9999.getGoodscode() != null && !mfGoods9999.getGoodscode().equals("")){
            criteria.andGoodscodeEqualTo(mfGoods9999.getGoodscode());
        }
        if(mfGoods9999.getGoodsname() != null && !mfGoods9999.getGoodsname().equals("")){
            criteria.andGoodsnameLike("%" + mfGoods9999.getGoodsname() + "%");
        }
        if(mfGoods9999.getClassname() != null && !mfGoods9999.getClassname().equals("")){
            criteria.andClassnameEqualTo(mfGoods9999.getClassname());
        }

        // 新增限制 条件
        List<String> strings = new ArrayList<>();

        if(mfGoodsLinks != null && mfGoodsLinks.size() != 0)
        {
            for (MFGoodsLink m:
                    mfGoodsLinks ) {
                strings.add(m.getGoodscode());
            }
        }

        criteria.andGoodscodeNotIn(strings);

       // List<MFGoods9999> mfGoods9999s =   mfGoods9999Mapper.selectByExample(mfGoods9999Example);
        log.info("是否去除已存入关联表数据（flag3 为1 去除）: " +  mfGoods9999.getFlag3());
        List<MFGoods9999> mfGoods9999s =   bdMapper.queryGoods(mfGoods9999.getGoodscode(),mfGoods9999.getGoodsname(),shopId,mfGoods9999.getClassname(),mfGoods9999.getFlag3(),null);
        // 去除所有维护表中数据

        logger.info(mfGoods9999s.toString());
        //  List<MFGoods9999> mfGoods9999s1 = companyService.selectCompanyAll(company);
        return getDataTable(mfGoods9999s);

    }

    // 新增关联关系
    /**
     * 新增客户
     */
    //@GetMapping("/add/{id}")
    @GetMapping("/add")
    /* public String add(@PathVariable("id") String id)*/
    public String add(@RequestParam("id") String id, ModelMap modelMap)
    {
        modelMap.put("key01",id);
        logger.info("新增关联关系：" + id);
        return prefix + "/add";
    }

    // 编辑关联关系
    /**
     * 新增客户
     */
    @GetMapping("/edit")
    public String edit()
    {
        logger.info("编辑页面");
        return prefix + "/edit";
    }

    // 增加药品关系
/*    @PostMapping("/addGoodLink")
    @ResponseBody
    @DataSource(value = DataSourceType.SLAVE)
    public AjaxResult addGoodLink(@Param("key1") String key1, @Param("key2") String key2, @Param("flag") String flag){
        // 获取 用户名 和  用户 部门
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        log.info("调用增加药品关系接口,参数1：" + key1 + "  参数2：" + key2 );
        // 数据处理
        // 以逗号分隔开的字符串转换成数组
        String[] key1Array = key1.split(",");
        String[] key2Array = key2.split(",");
        Date date = new Date();
        for(String s1 : key1Array){
            for (String s2 : key2Array){
                MFGoodsLink goodsLink = new MFGoodsLink();
                goodsLink.setGoodscode(s1);
                goodsLink.setShopid(sysUser.getDept().getDeptName());
                goodsLink.setShowflag(flag);
                goodsLink.setAddtime(date);
                goodsLink.setLinkgoodscode(s2);
                try {
                  //  mfGoodsLinkMapper.insert(goodsLink);
                    goodsLinksService.insert(goodsLink);
                }catch (Exception e){
                    e.printStackTrace();
                    return error("异常");
                }
            }
        }
        return success("成功");
    }*/

    // 增加药品关系
    @PostMapping("/addGoodLink")
    @ResponseBody
    @DataSource(value = DataSourceType.SLAVE)
    public AjaxResult addGoodLink(@Param("key1") String key1, @Param("key2") String key2, @Param("flag") String flag,@Param("templatename") String templatename){

        // 登录用户所在店号
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        log.info("调用增加药品关系接口,参数1：" + key1 + "  参数2：" + key2 );
        // 数据处理,
        // 以逗号分隔开的字符串转换成数组
        String[] key1Array = key1.split(",");
        //  String[] key2Array = key2.split(",");
        String[] key2Array ;
        List<LinkTemplate> linkTemplates = new ArrayList<>();

        // 用模板代替 key2
        if(!templatename.equals("") || templatename != null){
            logger.info("模板名：" + templatename);
            LinkTemplateExample linkTemplateExample = new LinkTemplateExample();
            LinkTemplateExample.Criteria criteria = linkTemplateExample.createCriteria();
            criteria.andShopidEqualTo(sysUser.getDept().getDeptName());
            criteria.andTemplatenameEqualTo(templatename);
            linkTemplates = linkTemplateMapper.selectByExample(linkTemplateExample);

            logger.info(linkTemplates.toString());

        }
        Date date = new Date();
        for(String s1 : key1Array){
            for (LinkTemplate template : linkTemplates ){
                MFGoodsLink goodsLink = new MFGoodsLink();
                goodsLink.setGoodscode(s1);
                goodsLink.setShopid(sysUser.getDept().getDeptName());
                goodsLink.setShowflag(template.getShowflag());
                goodsLink.setAddtime(date);
                goodsLink.setLinkgoodscode(template.getLinkgoodscode());
                try {

                    MFGoodsLinkExample mfGoodsLinkExample = new MFGoodsLinkExample();
                    MFGoodsLinkExample.Criteria criteria = mfGoodsLinkExample.createCriteria();
                    criteria.andShopidEqualTo(goodsLink.getShopid());
                    criteria.andGoodscodeEqualTo(goodsLink.getGoodscode());
                    criteria.andShowflagEqualTo(goodsLink.getShowflag());
                    criteria.andLinkgoodscodeEqualTo(goodsLink.getLinkgoodscode());
                    List<MFGoodsLink> mfGoodsLinks = mfGoodsLinkMapper.selectByExample(mfGoodsLinkExample);
                    if(mfGoodsLinks.size() == 0) {
                        mfGoodsLinkMapper.insert(goodsLink);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    return error("异常");
                }
            }
        }
        return success("成功");
    }

    // 查询药品关联关系
    @PostMapping("/queryGoodsLink")
    @ResponseBody
    @DataSource(value = DataSourceType.SLAVE)
    public List<MFGoods9999> queryGoodsLink(String goodsCode){
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        log.info("查询药品关联关系：参数1：" + goodsCode);
        //  goodsCode = "401-01-330";
        MFGoodsLinkExample goodsLinkExample = new MFGoodsLinkExample();
        MFGoodsLinkExample.Criteria criteria = goodsLinkExample.createCriteria();
        criteria.andGoodscodeEqualTo(goodsCode);
        List<MFGoodsLink> mfGoodsLinks = mfGoodsLinkMapper.selectByExample(goodsLinkExample);
        // 查询结果
        List<MFGoods9999> mfGoods9999s = new ArrayList<>();
        for (MFGoodsLink mfgl:
                mfGoodsLinks ) {
            MFGoods9999 mfGoods9999 = mfGoods9999Mapper.selectByPrimaryKey(new MFGoods9999Key(sysUser.getDept().getDeptName(),mfgl.getLinkgoodscode()));
            if(mfGoods9999 != null){
                mfGoods9999s.add(mfGoods9999);
            }
        }
        log.info(mfGoods9999s.toString());
/*        MFGoods9999 testData = new MFGoods9999();
        testData.setGoodsname("测试");
        mfGoods9999s.add(testData);*/

        return  mfGoods9999s;
    }

}

